package cn.qingyun.gis.modules.init.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.qingyun.gis.modules.init.system.entity.SysRoleState;
import cn.qingyun.gis.modules.init.system.entity.SysUserRole;
import cn.qingyun.gis.modules.init.system.service.ISysRoleStateService;
import cn.qingyun.gis.modules.init.system.service.ISysUserRoleService;
import cn.qingyun.gis.modules.init.system.vo.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author zhoudeli
 * @Date 2021/8/19 8:09
 * @Description 系统工具
 * @ClassName SystemUtil
 **/
@Slf4j
@Component
public class SystemUtil {
    private static ISysUserRoleService iSysUserRoleService;
    private static ISysRoleStateService iSysRoleStateService;

    public static LoginUser getCurrentUser() {
        try {
            return (LoginUser) SecurityUtils.getSubject().getPrincipal();
        } catch (Exception e) {
            return null;
        }
    }

    public static Expression getCurrentTenant() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            String tenantId = request.getHeader("tenant-id");
            if (StrUtil.isNotBlank(tenantId)) {
                return new LongValue(tenantId);
            }
        } catch (IllegalStateException e) {
            log.warn("获取当前 HttpServletRequest 失败", e);
        }
        return new NullValue();
    }

    public static Integer getCurrentTenant(HttpServletRequest request) {
        String tenantId = request.getHeader("tenant-id");
        if (StrUtil.isBlank(tenantId)) {
            throw new RuntimeException("当前用户未指定租户，请联系管理员");
        }
        return Integer.valueOf(tenantId);
    }

    public static List<Integer> getCurrnetAuthedStatus() {
        LoginUser currentUser = getCurrentUser();
        if (Objects.nonNull(currentUser)) {
            QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
            sysUserRoleQueryWrapper.lambda().eq(SysUserRole::getUserId, currentUser.getId());
            List<SysUserRole> userRoles = iSysUserRoleService.list(sysUserRoleQueryWrapper);

            if (CollUtil.isNotEmpty(userRoles)) {
                Set<String> roleIds = userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toSet());

                QueryWrapper<SysRoleState> sysRoleStateQueryWrapper = new QueryWrapper<>();
                sysRoleStateQueryWrapper.lambda().in(SysRoleState::getRoleId, roleIds);

                List<SysRoleState> roleStates = iSysRoleStateService.list(sysRoleStateQueryWrapper);
                if (CollUtil.isEmpty(roleStates)) {
                    throw new RuntimeException("当前角色未绑定流程状态，请联系管理员");
                }

                return roleStates.stream().map(SysRoleState::getProcStatus).distinct().collect(Collectors.toList());
            }
        }

        return Lists.newArrayList();
    }

    @Resource
    public void setiSysUserRoleService(ISysUserRoleService iSysUserRoleService) {
        SystemUtil.iSysUserRoleService = iSysUserRoleService;
    }

    @Resource
    public void setiSysRoleStateService(ISysRoleStateService iSysRoleStateService) {
        SystemUtil.iSysRoleStateService = iSysRoleStateService;
    }
}
